package cn.gaaidou.common.utils;

import org.reflections.Reflections;
import org.reflections.scanners.SubTypesScanner;

import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

/**
 * @author Martin
 * @date 2021/7/6 11:21
 */
public class ClazzUtil {

    private static final Map<Method, String> METHOD_NAME_CACHE = new ConcurrentHashMap<>();


    public static Set<Class<?>> getClazzByPackage(String packageName, Class interfaceClazz) {
        Reflections reflections = new Reflections(packageName, new SubTypesScanner(false));
        return reflections.getSubTypesOf(interfaceClazz);
    }

    /**
     * 获取方法完整描述的名字
     *
     * @param method
     * @return
     */
    public static String getMethodName(Method method) {
        if (method == null) {
            return null;
        }
        if (METHOD_NAME_CACHE.containsKey(method)) {
            return METHOD_NAME_CACHE.get(method);
        }
        Class<?> clazz = method.getDeclaringClass();
        String methodName = method.getName();
        Class<?>[] types = method.getParameterTypes();
        String pName = Arrays.stream(types).map(Class::getSimpleName).collect(Collectors.joining(","));
        String name = String.format("%s.%s(%s)", clazz.getName(), methodName, pName);
        METHOD_NAME_CACHE.putIfAbsent(method, name);
        return name;
    }
}
